<template>
  <div class="data-table-app-view">
    <div v-if="$slots.toolbar" class="data-table-app-view__toolbar" :style="toolbarStyle" @keydown.enter="onEnterKeyDown">
      <slot name="toolbar"></slot>
    </div>
    <slot></slot>
  </div>
</template>

<script>
import { isFullScreen } from '@/utils/fullscreen';

/*
创建带一个可选的工具栏、一个表格的一个可复用页面组件。

例子：
<data-table-app-view>
  <table-toolbar>...</table-toolbar>
  <data-table>...</data-table>
</data-table-app-view>
*/
export default {
  name: 'data-table-app-view',
  props: {
    toolbarStyle: {
      type: Object,
      default: () => ({})
    },
    containerSubtractHeight: {
      type: Number,
      default: 0
    }
  },
  beforeMount() {
    // 判断toolbar子组件如果已经有边距，就抵消toolbar的默认边距样式
    let toolbarVNode = this.$slots.toolbar && this.$slots.toolbar[0];
    if (toolbarVNode) {
      if (toolbarVNode.children == null
        || (toolbarVNode.children.length == 1 && toolbarVNode.children[0].componentOptions.tag == 'el-form')) {
        this.toolbarStyle.paddingBottom = '0px';
      } 
    }
  },
  mounted() {
    let toolbarVNode = this.$slots.toolbar && this.$slots.toolbar[0];
    let toolbarEl = toolbarVNode && toolbarVNode.elm.parentNode;

    let tableVNode = this.$slots.default.find((vnode) =>
      vnode.componentInstance && vnode.componentOptions.tag == 'data-table');
    let table = tableVNode.componentInstance;
    this.table = table;
    table.$el.children[0].style.overflow = 'auto';

    const onResize = () => {
      let restHeight = document.body.offsetHeight - (36 + 10 + this.containerSubtractHeight);
      if (!isFullScreen()) {
        restHeight -= 100;
      }
      if (toolbarEl) {
        restHeight -= toolbarEl.offsetHeight;
      }
      if (table.showPagination) {
        restHeight -= 28;
      }
      table.height = restHeight;
      this.$emit('resize', table.height);
    };

    this.$nextTick(onResize);
    window.addEventListener('resize', onResize);
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', onResize);
    });
  },
  methods: {
    onEnterKeyDown() {
      this.$emit('enter-keydown');
    }
  }
}
</script>

<style scoped>
.data-table-app-view__toolbar {
  padding-bottom: 8px;
}
</style>